/* eslint-disable no-param-reassign */
/* eslint-disable no-console */
import React, { useState } from 'react';
import { Input, Form, Box, Button, Card, NumberPicker } from '@alifd/next';
import { useStore } from '@/hooks';

const FormItem = Form.Item;
const formItemLayout = {
  colSpan: 12,
};

const DataForm = (props) => {
  const { dictItemStore: store } = useStore();
  const { dictId, editData = { sortWeight: 0 }, onSubmit, onCancel } = props;
  const [postData, setValue] = useState(editData);
  const editing = !!editData?.itemId;

  const formChange = (values) => {
    setValue(values);
  };

  const handleSubmit = (values, errors) => {
    if (errors) {
      console.log('🚀 _ file: DataForm.jsx:24 _ errors:', errors);
      return;
    }

    values.dictId = dictId;
    const promise = editing ? store.update(values) : store.create(values);
    promise.then(() => {
      // SUCC('提交成功');
      onSubmit && onSubmit();
    }).catch((e) => {
      FAIL(i18n.t('提交失败： ') + e);
    });
  };
  const handleCancel = () => {
    onCancel && onCancel();
  };

  return (
    <Card free style={{ border: 0 }}>
      <Card.Content>
        <Form colon style={{ width: 568, margin: '0 auto' }} responsive fullWidth value={postData} labelAlign="left" onChange={formChange}>
          <FormItem {...formItemLayout} label={i18n.t('字典项标识')} required requiredMessage="必填">
            <Input name="itemId" placeholder={i18n.t('请输入字典项标识')} validate="" readOnly={editing} />
          </FormItem>
          <FormItem {...formItemLayout} label={i18n.t('字典项名称')} required requiredMessage="必填">
            <Input name="name" placeholder={i18n.t('请输入字典项名称')} validate="" />
          </FormItem>
          <FormItem {...formItemLayout} label={i18n.t('排序值')} required requiredMessage="必填">
            <NumberPicker name="sortWeight" step={1} precision={3} />
          </FormItem>
          <FormItem {...formItemLayout} label={i18n.t('字典项说明')}>
            <Input name="description" placeholder={i18n.t('请输入字典项详细信息')} />
          </FormItem>

          <FormItem colSpan={12}>
            <Box spacing={8} direction="row" style={{ justifyContent: 'flex-end' }}>
              <Form.Submit type="primary" onClick={handleSubmit} validate>
                提交
              </Form.Submit>
              <Button onClick={handleCancel} type="secondary">
                取消
              </Button>
            </Box>
          </FormItem>
        </Form>
      </Card.Content>
    </Card >
  );
};

export default DataForm;
